<template>
  <div
    v-infinite-scroll="handleInfiniteOnLoad"
    class="demo-infinite-container"
    :infinite-scroll-disabled="busy"
    :infinite-scroll-distance="distance"
  >
    <a-list :data-source="data">
      <a-list-item slot="renderItem" slot-scope="item">
        <a-list-item-meta :description="item.equipmentNumber">
          <a slot="title" style="color: #39d3ee" @click="showInfo(item)">设备详情</a>
          <a-avatar slot="avatar" style="backgroundColor:#87d068" icon="user" />
        </a-list-item-meta>
        <div>{{ item.time }}</div>
      </a-list-item>
      <div v-if="loading && !busy" class="demo-loading-container">
        <a-spin />
      </div>
    </a-list>
  </div>
</template>

<script>
import infiniteScroll from 'vue-infinite-scroll'
import { getMessageByEquipment } from '@/api/message'
import { EventBus } from '@/views/dashboard/admin/components/eventBus'

export default {
  name: 'Message',
  directives: { infiniteScroll },
  props: {
    equipmentNumber: {
      type: String,
      default: '默认值'
    },
    ifSubscribeFlag: {
      type: Boolean,
      default: false // 默认没订阅
    }
  },
  data() {
    return {
      time: new Date(),
      data: [],
      loading: false,
      busy: false,
      list: {
        equipmentNumber: ''
      },
      count: 0,
      distance: 10,
      ifTimerFlag: true
    }
  },
  watch: {
    ifSubscribeFlag() {
      if (this.ifSubscribeFlag === true) {
        this.timer = setInterval(this.updateMessageList, 10000)
      } else {
        clearInterval(this.timer)
      }
    }
  },
  mounted() {

  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    updateMessageList() {
      this.busy = true
      this.getMessage()
    },
    getMessage() { //  得到订阅信息通过设备编号
      if (this.ifSubscribeFlag === true) {
        getMessageByEquipment(this.list).then(res => {
          const messageTime = new Date()
          this.time = messageTime.toLocaleString()
          const item = res.data
          this.data.push(item)
          this.busy = false
        })
      }
    },
    handleInfiniteOnLoad() {
      if (this.data.length > 5) {
        this.$message.warning('已经到底了')
      }
    },
    showInfo(item) {
      EventBus.$emit('aMsg', item)
      EventBus.$emit('ifSubscribeFlag', this.ifSubscribeFlag)
    }
  }
}
</script>

<style scoped>
.demo-infinite-container {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  padding: 8px 24px;
  height: 31em;
}
.demo-loading-container {
  position: absolute;
  bottom: 40px;
  width: 100%;
  text-align: center;
}
</style>
